<?php

namespace app\controller;

use app\exception\HttpResponseException;
use app\service\TaskV2Service;
use app\service\WorkbenchHistoryService;
use app\service\WorkbenchService;
use app\validate\WorkbenchValidate;
use support\Request;
use support\Response;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class WorkbenchController
{


    /**
     * @var WorkbenchService
     */
    private $workbenchService;
    private $workbenchHistoryService;
    private $taskV2Service;

    public function __construct()
    {
        $this->workbenchService = WorkbenchService::getInstance();
        $this->taskV2Service = TaskV2Service::getInstance();
        $this->workbenchHistoryService = WorkbenchHistoryService::getInstance();
    }


    /**
     * 组内完成情况
     * @param Request $request
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function groupPlanDoneCount(Request $request): Response
    {
        $param = query_array_construct([
            'project_id' => 'intval',
            'department_id' => 'intval',
            'todo_step_category_id_list' => 'split_array|array_map,intval',
            'start_time' => 'intval',
            'end_time' => 'intval',
            'today' => 'intval',
            'history' => 'strval',
        ], $request->post());

        $projectId = $param['project_id'];
        $departmentId = $param['department_id'];
        $todoStepCategoryIdList = $param['todo_step_category_id_list'];
        $startTime = $param['start_time'];
        $endTime = $param['end_time'];
        $today = $param['today'];
        if (!empty($param['history']) && $param['history'] == 'yes') {
            $res = $this->workbenchHistoryService->groupGroupPlanDoneCountHistoryCount($projectId, $request->getSaasUserId(), $todoStepCategoryIdList, $startTime, $endTime);
            return json(success_response('', $res));
        }
        $res = $this->workbenchService->groupPlanDoneCount($request, $projectId, $startTime, $endTime, $todoStepCategoryIdList, $departmentId, $today);
        return json(success_response('', $res));
    }

    /**
     * 部门交付情况
     * @param Request $request
     * @return Response
     * @throws DbException
     */
    public function groupDeliveryCount(Request $request): Response
    {
        $param = $request->post();
        $projectId = $param['project_id'] ?? 0;
        $departmentId = $param['department_id'] ?? 0;
        $todoStepCategoryIdList = param_to_array($param['todo_step_category_id_list'] ?? '', ',', 'intval');
        $startTime = $param['start_time'] ?? 0;
        $endTime = $param['end_time'] ?? 0;
        if (!empty($param['history']) && $param['history'] == 'yes') {
            $res = $this->workbenchHistoryService->groupDeliveryHistoryCount($projectId, $request->getSaasUserId(), $todoStepCategoryIdList, $startTime, $endTime);
            return json(success_response('', $res));
        }
        $res = $this->workbenchService->groupDeliveryCount($request, $projectId, $departmentId, $todoStepCategoryIdList, $startTime, $endTime);
        return json(success_response('', $res));
    }


    /**
     * 部门异常任务情况
     * @param Request $request
     * @return Response
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function groupAbnormalAddCount(Request $request): Response
    {
        $param = $request->post();

        $projectId = $param['project_id'] ?? 0;
        $departmentId = $param['department_id'] ?? 0;
        $todoStepCategoryIdList = param_to_array($param['todo_step_category_id_list'] ?? '', ',', 'intval');
        $startTime = $param['start_time'] ?? 0;
        $endTime = $param['end_time'] ?? 0;
        $today = $param['today'] ?? 0;

        $res = $this->workbenchService->groupAbnormalAddCount($request, $projectId, $departmentId, $todoStepCategoryIdList, $startTime, $endTime, $today);
        return json(success_response('', $res));
    }

    /**
     * 剧集详情
     * @param Request $request
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function episodeDetail(Request $request): Response
    {
        $param = $request->post();
        $projectId = $param['project_id'];
        $startTime = $param['start_time'];
        $endTime = $param['end_time'];
        $res = $this->workbenchService->episodeDetail($projectId, $startTime, $endTime);
        return json(success_response('', $res));
    }

    /**
     * 环节封板剧集情况查询
     * @param Request $request
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function stepCategorySealEpisodeList(Request $request): Response
    {
        $returnData = [];
        $param = $request->post();
        $res = $this->workbenchService->stepCategorySealEpisodeList($param);
        foreach ($res as $value) {
            $returnData[] = [
                'episode_id' => intval($value['episode_id'] ?? 0),
                'episode_name' => $value['episode_name'] ?? '',
                'episode_custom_grade' => $value['episode_custom_grade'] ?? '',
                'entity_total' => intval($value['entity_total'] ?? 0),
                'task_total' => intval($value['task_total'] ?? 0),
                'task_done' => intval($value['task_done'] ?? 0),
                'min_plan_start_time' => $value['min_plan_start_time'] ?? '',
                'max_plan_end_time' => $value['max_plan_end_time'] ?? '',
                'asset_task_count_detail_list' => $value['asset_task_count_detail_list'] ?? [],
                'review_meeting_name' => $value['review_meeting_name'] ?? '',
                'review_options_id' => intval($value['review_options_id'] ?? 0),
            ];
        }
        return json(success_response('', $returnData));
    }

    /**
     * 环节进行中剧集列表
     * @param Request $request
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function stepCategoryInProgressEpisodeList(Request $request): Response
    {
        $param = $request->post();
        $res = $this->workbenchService->stepCategoryInProgressEpisodeList($param);
        $returnData = [];
        foreach ($res as $value) {
            $returnData[] = [
                'episode_id' => intval($value['episode_id']),
                'episode_name' => $value['episode_name'] ?? '',
                'episode_custom_grade' => $value['episode_custom_grade'] ?? '',
                'entity_total' => $value['entity_total'] ?? 0,
                'task_total' => $value['task_total'] ?? 0,
                'task_done' => $value['task_done'] ?? 0,
                'min_plan_start_time' => intval($value['min_plan_start_time']),
                'max_plan_end_time' => intval($value['max_plan_end_time']),
                'asset_task_count_detail_list' => $value['asset_task_count_detail_list'] ?? [],
                'review_meeting_name' => $value['review_meeting_name'] ?? '',
                'review_options_id' => $value['review_options_id'] ?? 0,
            ];
        }
        return json(success_response('', $returnData));
    }

    /**
     * 制作情况概览
     * @param Request $request
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function makingOverview(Request $request): Response
    {
        $param = $request->post();
        $res = $this->workbenchService->makingOverview($param);
        return json(success_response('', $res));
    }

    /**
     * 全局异常统计
     * @param Request $request
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException|HttpResponseException
     */
    public function globalAbnormalCount(Request $request): Response
    {
        $param = $request->post();
        $queryCodeList = $param['query_code_list'];
        $v = new WorkbenchValidate();
        foreach ($queryCodeList as $code) {
            $sceneName = camelize($code);
            if (!method_exists($v, 'scene' . $sceneName)) {
                continue;
            }
            $v->scene($sceneName);
            if (!$v->check($param)) {
                throw_strack_exception($v->getError(), -400001);
            }
        }

        $res = $this->workbenchService->globalAbnormalCount($param);
        // 如果有时间区间查询,处理默认日期占位
        if (!empty($param['start_time']) && !empty($param['end_time'])) {
            $yearMonthDayList = get_month_day_list($param['start_time'], $param['end_time']);
            $res = array_map(function ($tmp) use ($yearMonthDayList, $param) {
                $countDataMap = array_column($tmp['count_data'] ?? [], null, 'date');
                foreach ($yearMonthDayList as $ymd) {
                    $countData[] = $countDataMap[$ymd] ?? ['number' => 0, 'project_id' => $param['project_id'] ?? 0, 'date' => $ymd];
                }
                $tmp['count_data'] = $countData ?? [];
                return $tmp;
            }, $res);
        }
        return json(success_response('success', $res));
    }

    /**
     * 个人任务统计列表
     * @param Request $request
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function personalTaskCount(Request $request): Response
    {
        $param = $request->post();
        $res = $this->workbenchService->personalTaskCount($param);
        return json(success_response('success', $res));
    }


    /**
     * 剧集封板播出情况列表
     * @param Request $request
     * @return Response
     * @throws DbException
     */
    public function episodeSealShowList(Request $request): Response
    {
        $param = $request->post();

        $projectId = $param['project_id'] ?? 0;
        $startTime = $param['start_time'] ?? 0;
        $endTime = $param['end_time'] ?? 0;

        $res = $this->workbenchService->episodeSealShowList($request, $projectId, $startTime, $endTime);
        return json(success_response('', $res));
    }

    /**
     * 未处理工单异常查询
     * @param Request $request
     * @return Response
     * @throws DbException
     */
    public function groupAbnormalWorkOrderCount(Request $request): Response
    {
        $param = $request->post();

        $projectId = $param['project_id'] ?? 0;
        $departmentId = $param['department_id'] ?? 0;
        $todoStepCategoryIdList = param_to_array($param['todo_step_category_id_list'] ?? '', ',', 'intval');
        $startTime = $param['start_time'] ?? 0;
        $endTime = $param['end_time'] ?? 0;
        $today = $param['today'] ?? 0;

        $res = $this->workbenchService->groupAbnormalWorkOrderCount($request, $projectId, $departmentId, $todoStepCategoryIdList, $startTime, $endTime, $today);
        return json(success_response('', $res));
    }

    /**
     * 延期任务数
     * @param Request $request
     * @return Response
     * @throws DbException
     */
    public function groupAbnormalDelayTaskCount(Request $request): Response
    {
        $param = $request->post();

        $projectId = $param['project_id'] ?? 0;
        $departmentId = $param['department_id'] ?? 0;
        $todoStepCategoryIdList = param_to_array($param['todo_step_category_id_list'] ?? '', ',', 'intval');
        $startTime = $param['start_time'] ?? 0;
        $endTime = $param['end_time'] ?? 0;
        $today = $param['today'] ?? 0;

        $res = $this->workbenchService->groupAbnormalDelayTaskCount($request, $projectId, $departmentId, $todoStepCategoryIdList, $startTime, $endTime, $today);
        return json(success_response('', $res));
    }

    /**
     * 上游交付情况
     * @param Request $request
     * @return Response
     * @throws DbException
     */
    public function groupUpstreamDeliveryCount(Request $request): Response
    {
        $param = query_array_construct([
            'project_id' => 'intval',                                           // 项目ID
            'department_id' => 'intval',                                        // 部门ID
            'todo_step_category_id_list' => 'split_array|array_map,intval',     // 环节ID 列表
            'start_time' => 'intval',
            'end_time' => 'intval',
            'today' => 'intval',
            'history' => 'strval',                                              // 是否历史
        ], $request->post());

        $projectId = $param['project_id'];
        $departmentId = $param['department_id'];
        $todoStepCategoryIdList = $param['todo_step_category_id_list'];
        $startTime = $param['start_time'];
        $endTime = $param['end_time'];
        $today = $param['today'];

        $res = $this->workbenchService->groupUpstreamDeliveryCount($request, $param, $projectId, $departmentId, $todoStepCategoryIdList, $startTime, $endTime, $today);
        return json(success_response('', $res));
    }

    /**
     * 上游标准任务交付情况
     * @param Request $request
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function groupUpstreamTodoDeliveryCount(Request $request): Response
    {
        $param = query_array_construct([
            'project_id' => 'intval',                                           // 项目ID
            'department_id' => 'intval',                                        // 部门ID
            'todo_step_category_id_list' => 'split_array|array_map,intval',     // 环节ID 列表
            'start_time' => 'intval',
            'end_time' => 'intval',
            'today' => 'intval',
            'history' => 'strval',                                              // 是否历史
            'data_type' => 'strval',                                              // 数据格式 count-统计 list-列表
        ], $request->post());

        $projectId = $param['project_id'];
        $departmentId = $param['department_id'];
        $todoStepCategoryIdList = $param['todo_step_category_id_list'];
        $startTime = $param['start_time'];
        $endTime = $param['end_time'];

        $res = $this->workbenchService->groupUpstreamTodoDeliveryCount($request, $param, $projectId, $departmentId, $todoStepCategoryIdList, $startTime, $endTime);
        return json(success_response('', $res));
    }

    /**
     * 今日异常任务统计
     * @param Request $request
     * @return Response
     */
    public function todayAbnormalTaskCount(Request $request): Response
    {
        $param = query_array_construct([
            'project_id' => 'intval',                                           // 项目ID
            'department_id' => 'intval',                                        // 部门ID
            'todo_step_category_id_list' => 'split_array|array_map,intval',     // 环节ID 列表
            'episode_id' => 'split_array|array_map,strval',
            'task_step_type' => 'split_array|array_map,strval',                 // 任务类型
            'query_category' => 'strval',                                       // 查询类型
            'query_type' => 'strval',                                       //
            'start_time' => 'intval',
            'end_time' => 'intval',
            'history' => 'strval',
        ], $request->post());

        if (empty($param['task_step_type'])) {
            $param['task_step_type'] = ['step', 'to_do'];
        }
        $res = $this->workbenchService->taskAbnormalCount($request, $param);
        return json(success_response('', $res));
    }

    /**
     * 环节审核中的剧集情况
     * @param Request $request
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function stepCategoryReviewingEpisodeList(Request $request): Response
    {
        $param = $request->post();
        $res = $this->workbenchService->stepCategoryReviewingEpisodeList($param);
        return json(success_response('', $res));
    }

    /**
     * 与我相关任务统计
     * @param Request $request
     * @return Response
     */
    public function getTaskMemberCount(Request $request): Response
    {
        $param = $request->post();
        $param = $param['param'];
        $responseFormatType = $param['response_format_type'];
        $code = $param['code'] ?? '';
        $filter = $param['filter'] ?? [];
        $page = $param['page'] ?? [0, 50];
        $limit = $param['limit'] ?? 100;
        $fields = $param['fields'] ?? '';
        $rangeTime = $param['range_time'] ?? [0, 0];
        $res = $this->taskV2Service->getTaskMemberCount($fields, $responseFormatType, $code, $rangeTime, $filter,  $page, $limit);
        return json(success_response('', $res));
    }
}
